<%#
 Copyright 2013-2018 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
<%_
const query = generateEntityQueries(relationships, entityInstance, dto);
const queries = query.queries;
const variables = query.variables;
let hasManyToMany = query.hasManyToMany;
_%>
import { Component, OnInit<% if (fieldsContainImageBlob) { %>, ElementRef<% } %> } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
<%_ if ( fieldsContainDate ) { _%>
import * as moment from 'moment';
    <%_ if ( fieldsContainInstant || fieldsContainZonedDateTime ) { _%>
import { DATE_TIME_FORMAT } from 'app/shared/constants/input.constants';
    <%_ } _%>
<%_ } _%>
<%_ if (queries && queries.length > 0 || fieldsContainBlob) { _%>
import { <% if (queries && queries.length > 0) { %>JhiAlertService, <% } %><% if (fieldsContainBlob) { %>JhiDataUtils<% } %> } from 'ng-jhipster';
<%_ } _%>

import { I<%= entityAngularName %> } from 'app/shared/model/<%= entityModelFileName %>.model';
import { <%= entityAngularName %>Service } from './<%= entityFileName %>.service';
<%_
let hasRelationshipQuery = false;
Object.keys(differentRelationships).forEach(key => {
    const hasAnyRelationshipQuery = differentRelationships[key].some(rel =>
        (rel.relationshipType === 'one-to-one' && rel.ownerSide === true && rel.otherEntityName !== 'user')
            || rel.relationshipType !== 'one-to-many'
    );
    if (hasAnyRelationshipQuery) {
        hasRelationshipQuery = true;
    }
    if (differentRelationships[key].some(rel => rel.relationshipType !== 'one-to-many')) {
        const uniqueRel = differentRelationships[key][0];
        if (uniqueRel.otherEntityAngularName !== entityAngularName) {
            if (uniqueRel.otherEntityAngularName === 'User') {
_%>
import { I<%= uniqueRel.otherEntityAngularName %>, <%= uniqueRel.otherEntityAngularName%>Service } from 'app/core';
<%_         } else { _%>
import { I<%= uniqueRel.otherEntityAngularName %> } from 'app/shared/model/<%= uniqueRel.otherEntityModelName %>.model';
import { <%= uniqueRel.otherEntityAngularName%>Service } from 'app/entities/<%= uniqueRel.otherEntityPath %>';
<%_         }
        }
    }
}); _%>

@Component({
    selector: '<%= jhiPrefixDashed %>-<%= entityFileName %>-update',
    templateUrl: './<%= entityFileName %>-update.component.html'
})
export class <%= entityAngularName %>UpdateComponent implements OnInit {

    <%= entityInstance %>: I<%= entityAngularName %>;
    isSaving: boolean;
    <%_
    for ( const idx in variables ) { %>
    <%- variables[idx] %>
    <%_ } _%>
    <%_ for ( idx in fields ) {
        const fieldName = fields[idx].fieldName;
        const fieldType = fields[idx].fieldType;
        if ( fieldType === 'LocalDate' ) { _%>
    <%= fieldName %>Dp: any;
    <%_ } else if ( ['Instant', 'ZonedDateTime'].includes(fieldType) ) { _%>
    <%= fieldName %>: string;
      <%_ } _%>
    <%_ } _%>

    constructor(
        <%_ if (fieldsContainBlob) { _%>
        protected dataUtils: JhiDataUtils,
        <%_ } _%>
        <%_ if (queries && queries.length > 0) { _%>
        protected jhiAlertService: JhiAlertService,
        <%_ } _%>
        protected <%= entityInstance %>Service: <%= entityAngularName %>Service,
        <%_ Object.keys(differentRelationships).forEach(key => {
            if (differentRelationships[key].some(rel => rel.relationshipType !== 'one-to-many')) {
                const uniqueRel = differentRelationships[key][0];
                if (uniqueRel.otherEntityAngularName !== entityAngularName) { _%>
        protected <%= uniqueRel.otherEntityName %>Service: <%= uniqueRel.otherEntityAngularName %>Service,
        <%_
                }
            }
        }); _%>
        <%_ if (fieldsContainImageBlob) { _%>
        protected elementRef: ElementRef,
        <%_ } _%>
        protected activatedRoute: ActivatedRoute
    ) {
    }

    ngOnInit() {
        this.isSaving = false;
        this.activatedRoute.data.subscribe(({<%= entityInstance %>}) => {
            this.<%= entityInstance %> = <%= entityInstance %>;
<%_ for (idx in fields) {
    const fieldName = fields[idx].fieldName;
    const fieldType = fields[idx].fieldType;
    if (['Instant', 'ZonedDateTime'].includes(fieldType)) { _%>
            this.<%= fieldName %> = this.<%= entityInstance %>.<%= fieldName %> != null ? this.<%= entityInstance %>.<%= fieldName %>.format(DATE_TIME_FORMAT) : null;
    <%_ } _%>
<%_ } _%>
        });
        <%_ for (idx in queries) { _%>
        <%- queries[idx] %>
        <%_ } _%>
    }

    <%_ if (fieldsContainBlob) { _%>
    byteSize(field) {
        return this.dataUtils.byteSize(field);
    }

    openFile(contentType, field) {
        return this.dataUtils.openFile(contentType, field);
    }

    setFileData(event, entity, field, isImage) {
        this.dataUtils.setFileData(event, entity, field, isImage);
    }

    <%_ if (fieldsContainImageBlob) { _%>
    clearInputImage(field: string, fieldContentType: string, idInput: string) {
        this.dataUtils.clearInputImage(this.<%= entityInstance %>, this.elementRef, field, fieldContentType, idInput);
    }

    <%_ } _%>
    <%_ } _%>
    previousState() {
        window.history.back();
    }

    save() {
        this.isSaving = true;
        <%_ for (idx in fields) {
            const fieldName = fields[ idx ].fieldName;
            const fieldType = fields[idx].fieldType;
            if ([ 'Instant', 'ZonedDateTime' ].includes(fieldType)) { _%>
                this.<%= entityInstance %>.<%= fieldName %> = this.<%= fieldName %> != null ? moment(this.<%= fieldName %>, DATE_TIME_FORMAT) : null;
        <%_ }
        } _%>
        if (this.<%= entityInstance %>.id !== undefined) {
            this.subscribeToSaveResponse(
                this.<%= entityInstance %>Service.update(this.<%= entityInstance %>));
        } else {
            this.subscribeToSaveResponse(
                this.<%= entityInstance %>Service.create(this.<%= entityInstance %>));
        }
    }

    protected subscribeToSaveResponse(result: Observable<HttpResponse<I<%= entityAngularName %>>>) {
        result.subscribe((res: HttpResponse<I<%= entityAngularName %>>) =>
            this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError());
    }

    protected onSaveSuccess() {
        this.isSaving = false;
        this.previousState();
    }

    protected onSaveError() {
        this.isSaving = false;
    }
    <%_ if (queries && queries.length > 0) { _%>

    protected onError(errorMessage: string) {
        this.jhiAlertService.error(errorMessage, null, null);
    }
    <%_ } _%>
    <%_
    const entitiesSeen = [];
    for (idx in relationships) {
        const otherEntityNameCapitalized = relationships[idx].otherEntityNameCapitalized;
        if (relationships[idx].relationshipType !== 'one-to-many' && !entitiesSeen.includes(otherEntityNameCapitalized)) {
    _%>

    track<%= otherEntityNameCapitalized %>ById(index: number, item: I<%= relationships[idx].otherEntityAngularName %>) {
        return item.id;
    }
    <%_ entitiesSeen.push(otherEntityNameCapitalized); } } _%>
    <%_ if (hasManyToMany) { _%>

    getSelected(selectedVals: Array<any>, option: any) {
        if (selectedVals) {
            for (let i = 0; i < selectedVals.length; i++) {
                if (option.id === selectedVals[i].id) {
                    return selectedVals[i];
                }
            }
        }
        return option;
    }
    <%_ } _%>
}
